//
//  HMComposeViewControllew.swift
//  微博
//
//  Created by 程双岐 on 16/9/28.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewControllew: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        // Do any additional setup after loading the view.
    }

    fileprivate lazy var emoticonKetBoard: HMEmoticonKeyBoard = {
       let view = HMEmoticonKeyBoard()
        view.size = CGSize(width: self.textView.width, height:216)
        return view
    }()
    
    fileprivate lazy var textView: HMComposetextView = {
        let text = HMComposetextView()
        text.placeHolder = "呵呵呵呵呵呵呵呵呵呵呵"
        text.font = UIFont.systemFont(ofSize: 14)
        text.delegate = self
        text.alwaysBounceVertical = true
       return text
    }()
    
    @available(iOS 9.0, *)
    fileprivate lazy var toolBar: HMComposeToolBar = {
        let tool = HMComposeToolBar()
        return tool
        
    }()
    
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(btnSendAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.size = CGSize(width: 45, height: 35)
        
        return button
    }()
    
    private lazy var titleLabel: UILabel = {
       let label = UILabel(textColor: UIColor.darkGray, fontSize: 16)
        if let name = HMUserAccpuntViewModel.sharedUserAccountViewModel.useraccount?.name{
            let result = "发微博\n" + name
           let range = (result as NSString).range(of: name)
            
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: result)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName: UIColor.brown], range: range)
            label.attributedText = attributedStr

        }else{
            label.text = "发微博"

        }
        label.numberOfLines = 0
        label.sizeToFit()
        label.textAlignment = .center
        return label
    }()
    
    fileprivate lazy var pictureView: HMComposePictureView = {
    
        let view = HMComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    
    private func setupNavUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        navigationItem.titleView = titleLabel
    }
    fileprivate func setupUI() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonNoti(noti:)), name: NSNotification.Name(DidSelectedEmoticonNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmoticonNoti), name: NSNotification.Name(DidSelectedDeleteEmoticonNotification), object: nil)
        setupNavUI()
        view.backgroundColor = UIColor.white
        view.addSubview(textView)
        if #available(iOS 9.0, *) {
            view.addSubview(toolBar)
        } else {
            // Fallback on earlier versions
        }
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(view)
            make.left.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        if #available(iOS 9.0, *) {
            toolBar.snp_makeConstraints { (make) in
                
                make.trailing.equalTo(textView)
                make.leading.equalTo(textView)
                make.bottom.equalTo(self.view)
                make.height.equalTo(35)
            }
        } else {
            // Fallback on earlier versions
        }
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)

        }
        
        if #available(iOS 9.0, *) {
            toolBar.callBack = { [weak self] (type: HMComposeToolBarButtonType) in
                switch type {
                case .picture:
                    print("ccc")
                    self?.didSelectedPicture()
                case .mention:
                    print("ccc")
                case .trend:
                    print("ccc")
                case .emoticon:
                    print("ccc")
                    self?.didSelectedEmoticon()
                case .add:
                    print("ccc")
                }
            }
        } else {
            // Fallback on earlier versions
        }
        pictureView.lastCellCallBack = { [weak self] in
            //  打开图片浏览器
            self?.didSelectedPicture()
        }
        
        
    }
    @objc private func cancelAction(){
        self.view.endEditing(true)
        self.dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func btnSendAction(){
        let accessToken = HMUserAccpuntViewModel.sharedUserAccountViewModel.useraccount?.access_token
        let text = textView.emoticonText
        //遍历富文本通过文本附件获取对应的表情模型
        
//        var result = ""
//        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: []) { (info, range, _) in
//            if let attachement = info["NSAttachment"] as? HMTextAttachment{
//                let chs = attachement.emoticon?.chs
//                result += chs!
//            }else{
//                let text = textView.attributedText.attributedSubstring(from: range).string
//                result += text
//            }
//        }
        
        
        
        if pictureView.images.count > 0 {
            
            let firstImage = pictureView.images.first!
            
            HMNetWorkTools.sharedTool.upload(access_token: accessToken!, status: text, image: firstImage, callBack: { (response, error) in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    print(error)
                    return
                }
                
                //  上传成功
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                
                
            })
            
            
            
        } else {
            
            
            
            SVProgressHUD.show()
            HMNetWorkTools.sharedTool.update(access_token: accessToken!, status: text, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "网络请求异常!")
                    return
                }
                
                //  代码执行到此,表示发送成功
                SVProgressHUD.showSuccess(withStatus: "发送成功!")
            })


        }
    }
    
    @objc private func didSelectedEmoticonNoti(noti: Notification) {
        
        guard let emoticon = noti.object as? HMEmoticon else {
            return
        }
        textView.insertEmoticon(emoticon: emoticon)
        
        HMEmoticonTools.shareTools.saveRecentEmoticon(emoticon: emoticon)


        //通知去刷新表情试图去刷新最近表情的数据
        
        emoticonKetBoard.reloadRecentData()
    }
    
    @objc private func didSelectedDeleteEmoticonNoti() {
        
        //  删除内容
        textView.deleteBackward()
        
    }
    
    
    @objc private func keyBoardFrameChange(noti: Notification){
        print(noti.userInfo)
        //键盘的frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).cgRectValue
        //键盘的动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        if #available(iOS 9.0, *) {
            toolBar.snp_updateConstraints { (make) in
                make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScrenHeight)
            }
        } else {
            // Fallback on earlier versions
        }
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension HMComposeViewControllew: UIImagePickerControllerDelegate,UINavigationControllerDelegate  {
    
    func didSelectedEmoticon() {
        if textView.inputView == nil {
            textView.inputView = emoticonKetBoard
            if #available(iOS 9.0, *) {
                toolBar.showIcon(isEmoticon: true)
            } else {
                // Fallback on earlier versions
            }
        }else{
            textView.inputView = nil
            if #available(iOS 9.0, *) {
                toolBar.showIcon(isEmoticon: false)
            } else {
                // Fallback on earlier versions
            }

        }
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
    
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        
        imagePictureCtr.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            imagePictureCtr.sourceType = .camera

        }else{
            imagePictureCtr.sourceType = .photoLibrary
        }
        
        //是否支持前置和后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            print("支持前置")
        }
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
                print("支持后置")
        }
        //允许编辑
//        imagePictureCtr.allowsEditing = true
        
        
        self.present(imagePictureCtr, animated: true, completion: nil)
        
        
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)

        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info["UIImagePickerControllerOriginalImage"]! as! UIImage
        //  获取压缩后的图片
        let scaleImage = image.scaleImage(scaleWidth: 200)
        
        //  添加压缩后的图片显示
        pictureView.addImage(image: scaleImage)
        
        
        
        picker.dismiss(animated: true, completion: nil)
    }
    
}

extension HMComposeViewControllew: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)

    }
}

